package cn.zou.db;

import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * Created by zou on 2017/7/13.
 */
public class TableLoad {
    /**
     * 加载配置文件中的内容 应当前程安全
     * @param fileNames 属性字段名
     * @return
     */
    public synchronized Map<String,Object>  loadCloum(String[] fileNames,Class clazz){
        ArrayList<String> pklist=new ArrayList<String>();
        HashMap<String,Object>  map=new HashMap<String, Object>();
        Properties properties = getProperties(clazz);
        String tableName = properties.getProperty("tableName");
        map.put("tableName",tableName);
        for(String fileName:fileNames){
            String property = properties.getProperty(fileName);
            map.put(fileName,property);
        }
        String property = properties.getProperty("pk");
        String[] split = property.split(",");
        for(String pk:split){
            pklist.add(pk);
        }
        map.put("pk",pklist);
        return map;
    }
    private  Properties getProperties(Class clazz){
        try {
            InputStream is=new BufferedInputStream(new FileInputStream(new File(getPath(clazz))));
            Properties p=new Properties();
            p.load(is);
            return p;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取到配置文件路径
     * @param clazz
     * @return
     */
    private String getPath(Class clazz){
        String path = this.getClass().getResource("").toString();
        int i = path.indexOf("/class");
        String substring = path.substring(0, i);
        String s = substring.replaceAll("file:/", "");
        return s+"/src/config/"+clazz.getSimpleName()+".properties";
    }
    public  Object loadOneCloum(Class clazz,String fieldName){
        Properties properties = getProperties(clazz);
        return properties.get(fieldName);
    }
}
